<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col><el-button type="primary">添加角色</el-button></el-col>
      </el-row>
      <!-- 角色列表渲染 -->
      <el-table :data="userRightsList" border style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(oneItem, oneId) in scope.row.children"
              :key="oneItem.id"
              :class="[
                'vcenter',
                'borderBottom',
                oneId === 0 ? 'borderTop' : '',
              ]"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="deleteRightsAdmin(scope.row, oneItem.id)"
                  >{{ oneItem.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二,三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="twoItem in oneItem.children"
                  :key="twoItem.id"
                  :class="['borderBottom', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRightsAdmin(scope.row, twoItem.id)"
                      >{{ twoItem.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="twoItemChild in twoItem.children"
                      :key="twoItemChild.id"
                      closable
                      type="warning"
                      @close="deleteRightsAdmin(scope.row, twoItemChild.id)"
                      >{{ twoItemChild.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">
              编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-bangzhu"
              size="mini"
              @click="dialogAddUserRigths(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogSetAddUserRigths"
      width="45%"
      @close="ClearArrData"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="giveUserRights"
        show-checkbox
        node-key="id"
        :props="treeProps"
        default-expand-all
        :default-checked-keys="addUserRights"
        ref="treeIdRefs"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSetAddUserRigths = false">取 消</el-button>
        <el-button type="primary" @click="updateUserRgihts">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      userRightsList: [],
      // 分配权限对话框展示与隐藏
      dialogSetAddUserRigths: false,
      // 分配权限数据保存
      giveUserRights: [],
      // 树形控件绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件中选中id的值
      addUserRights: [],
      // 当前对话框的id
      addUserRightsIdNow: ''
    }
  },
  created() {
    this.getUserRightsList()
  },
  methods: {
    async getUserRightsList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.success('获取角色列表失败!')
      }
      this.userRightsList = res.data
    },
    // 删除权限
    deleteRightsAdmin(role, rightsId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightsId}`
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败!')
          //   this.getUserRightsList() 会引起页面整体刷新
          role.children = res.data //
          this.$message.success('删除成功!')
        })
        .catch(() => {
          this.$message.success('已取消删除')
        })
    },
    async dialogAddUserRigths(role) {
      // 保存当前对话框的用户id
      this.addUserRightsIdNow = role.id

      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据列表失败！')
      }
      this.giveUserRights = res.data
      // 通过递归获取三级列表中的id
      this.getUserRigthsId(role, this.addUserRights)
      this.dialogSetAddUserRigths = true
    },
    // 获取用户权限三级列表中的权限id，通过递归
    getUserRigthsId(data, arr) {
      // 判断数据中是否存在children,如果当前数据中不包含children节点，就是三级节点
      if (!data.children) {
        return arr.push(data.id)
      }
      data.children.forEach((element) => {
        this.getUserRigthsId(element, arr)
      })
    },
    // 关闭用户对话框清理数据残留
    ClearArrData() {
      this.addUserRights = []
    },
    // 点击确定更新用户权限
    async updateUserRgihts() {
      const keys = [
        ...this.$refs.treeIdRefs.getCheckedKeys(),
        ...this.$refs.treeIdRefs.getHalfCheckedKeys()
      ]
      const keyStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.addUserRightsIdNow}/rights`,
        {
          rids: keyStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户权限失败！请稍后再试')
      }
      // 重新获取角色列表，渲染页面
      // TODO 实现数据局部更新，不影响数据整体刷新
      this.getUserRightsList()
      this.$message.success('更新用户权限成功！')
      // 关闭对话框
      this.dialogSetAddUserRigths = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.borderTop {
  border-top: 1px solid #eee;
}
.borderBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
